package com.zqxq.lottery.service.user.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayFundTransToaccountTransferRequest;
import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.zqxq.common.constant.Result;
import com.zqxq.common.enums.CodeEnum;
import com.zqxq.common.utils.DispatcherUtils;
import com.zqxq.lottery.config.WechatConfig;
import com.zqxq.lottery.entity.po.order.TradeInfoPO;
import com.zqxq.lottery.entity.po.user.UserAlipayPO;
import com.zqxq.lottery.entity.po.user.UserFundsPO;
import com.zqxq.lottery.entity.po.user.UserInfoPO;
import com.zqxq.lottery.entity.po.user.UserWechatPO;
import com.zqxq.lottery.mapper.user.UserAlipayMapper;
import com.zqxq.lottery.mapper.user.UserFundsMapper;
import com.zqxq.lottery.mapper.user.UserInfoMapper;
import com.zqxq.lottery.mapper.user.UserWechatMapper;
import com.zqxq.lottery.service.order.ITradeInfoService;
import com.zqxq.lottery.service.user.IUserAlipayService;
import com.zqxq.lottery.service.user.IUserFundsService;
import com.zqxq.lottery.service.user.IUserWechatService;
import com.zqxq.lottery.util.CertHttpUtil;
import com.zqxq.lottery.util.HttpUtil;
import com.zqxq.lottery.util.WechatUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


@Service
@Slf4j
public class UserWechatServiceImpl extends ServiceImpl<UserWechatMapper,UserWechatPO> implements IUserWechatService {

    @Autowired
    private UserFundsMapper userFundsMapper;
    @Autowired
    private WechatConfig wechatConfig;
    @Autowired
    private ITradeInfoService tradeInfoService;
    @Autowired
    private IUserFundsService userFundsService;

    @Override
    public void bindWechat(long userId, String unionId, String openId) {
        UserWechatPO userWechatPO = new UserWechatPO();
        userWechatPO.setUser_id(userId);
        userWechatPO.setOpen_id(openId);
        userWechatPO.setUnion_id(unionId);
        userWechatPO.setId(userId);
        insertOrUpdate(userWechatPO);
        //修改是否绑定
        UserFundsPO userFundsPO = new UserFundsPO();
        userFundsPO.setUser_id(userId);
        userFundsPO.setWechat_bind(1);
        userFundsMapper.updateById(userFundsPO);
    }

    @Override
    public Result saveTransferMoney(HttpServletRequest request, Long userId, Long cashId, BigDecimal money, String account) {
        try{
            Map<String,String> map = new HashMap<>();
            String nonceStr = UUID.randomUUID().toString().substring(0, 32);
            String outTradeNo = String.valueOf(cashId);
            String url = wechatConfig.getDrawCashUrl();
            String appId = wechatConfig.getAppId();
            String mchId= wechatConfig.getMchId();
            String key = wechatConfig.getKey();
            String certPath = wechatConfig.getCertPath();
            String amount = DispatcherUtils.parseString(money.multiply(new BigDecimal(100)).intValue());
            map.put("mch_appid", appId);
            map.put("mchid", mchId);
            map.put("nonce_str",nonceStr);
            map.put("partner_trade_no", outTradeNo);
            map.put("openid", account);
            map.put("check_name","NO_CHECK");
            map.put("amount", amount);
            map.put("desc", "提现");
            map.put("spbill_create_ip", request.getRemoteAddr());
            String paySign = WechatUtil.getPayCustomSign(map,key);
            map.put("sign",paySign);
            String xml= WechatUtil.ArrayToXml(map);
            String returnXmlStr = CertHttpUtil.postData(url,xml,mchId,certPath);
            Map<String, String> returnMap = WechatUtil.doXMLParse(returnXmlStr);
            System.out.println("returnMap:"+returnMap);
            String resultCode = returnMap.get("result_code");
            TradeInfoPO tradeInfoPO = new TradeInfoPO();
            tradeInfoPO.setUser_id(userId);
            tradeInfoPO.setTrade_no(returnMap.get("partner_trade_no"));
            tradeInfoPO.setTrade_way(2);
            tradeInfoPO.setTrade_type(3);
            tradeInfoPO.setOrder_id(cashId);
            tradeInfoPO.setAmount(money.setScale(2,4));
            tradeInfoPO.setResult(resultCode);
            tradeInfoPO.setData(returnXmlStr);
            tradeInfoPO.setCreate_time(new Date());
            tradeInfoService.insert(tradeInfoPO);
            if(resultCode.equals("SUCCESS")){
                System.out.println("调用成功");
                userFundsService.saveDrawCashSuccess(cashId);
            } else {
                userFundsService.saveDrawCashFail(userId,cashId, returnMap.get("err_code_des"), money);
                return new Result(10010, "提现失败");
            }
        }catch (Exception e) {
            log.error("transferMoney is error!", e);
            return new Result(CodeEnum.FAIL_100005.getCode(), CodeEnum.FAIL_100005.getMsg());
        }
        return new Result();
    }
}
